package xorm

import (
	"math/rand"
	"sync"
	"time"
)

// IPolicy 主从数据库读写分离，EngineGroup的负载策略。
type IPolicy interface {
	Node(*EngineGroup) *Engine
}

// PolicyHandler should be used when a function is a GroupPolicy
type PolicyHandler func(*EngineGroup) *Engine

// Subordinate implements the chosen of subordinates
func (h PolicyHandler) Node(eg *EngineGroup) *Engine {
	return h(eg)
}

// RandomPolicy 随机访问负载策略。
func RandomPolicy() PolicyHandler {
	var r = rand.New(rand.NewSource(time.Now().UnixNano()))
	return func(g *EngineGroup) *Engine {
		return g.Slaves()[r.Intn(len(g.Slaves()))]
	}
}

// WeightRandomPolicy 权重随机访问负载策略。
func WeightRandomPolicy(weights []int) PolicyHandler {
	var rands = make([]int, 0, len(weights))
	for i := 0; i < len(weights); i++ {
		for n := 0; n < weights[i]; n++ {
			rands = append(rands, i)
		}
	}
	var r = rand.New(rand.NewSource(time.Now().UnixNano()))
	return func(g *EngineGroup) *Engine {
		var subordinates = g.Slaves()
		idx := rands[r.Intn(len(rands))]
		if idx >= len(subordinates) {
			idx = len(subordinates) - 1
		}
		return subordinates[idx]
	}
}

// RoundRobinPolicy 轮询访问负载策略。
func RoundRobinPolicy() PolicyHandler {
	var pos = -1
	var lock sync.Mutex
	return func(g *EngineGroup) *Engine {
		var subordinates = g.Slaves()

		lock.Lock()
		defer lock.Unlock()
		pos++
		if pos >= len(subordinates) {
			pos = 0
		}

		return subordinates[pos]
	}
}

// WeightRoundRobinPolicy 权重轮询访问负载策略。
func WeightRoundRobinPolicy(weights []int) PolicyHandler {
	var rands = make([]int, 0, len(weights))
	for i := 0; i < len(weights); i++ {
		for n := 0; n < weights[i]; n++ {
			rands = append(rands, i)
		}
	}
	var pos = -1
	var lock sync.Mutex

	return func(g *EngineGroup) *Engine {
		var subordinates = g.Slaves()
		lock.Lock()
		defer lock.Unlock()
		pos++
		if pos >= len(rands) {
			pos = 0
		}

		idx := rands[pos]
		if idx >= len(subordinates) {
			idx = len(subordinates) - 1
		}
		return subordinates[idx]
	}
}

// LeastConnPolicy 最小连接数访问负载策略。
func LeastConnPolicy() PolicyHandler {
	return func(g *EngineGroup) *Engine {
		var subordinates = g.Slaves()
		connections := 0
		idx := 0
		for i := 0; i < len(subordinates); i++ {
			openConnections := subordinates[i].DB().Stats().OpenConnections
			if i == 0 {
				connections = openConnections
				idx = i
			} else if openConnections <= connections {
				connections = openConnections
				idx = i
			}
		}
		return subordinates[idx]
	}
}
